<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="所属软件" prop="baseInfoId">
        <el-select
          v-model="queryParams.baseInfoId"
          placeholder="请选择所属软件"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in baseInfoOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.COMPO_SOFTWARE_FILE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="文件夹" prop="dirId">
        <el-tree-select
          v-model="queryParams.dirId"
          :data="fileDirTree"
          :props="defaultProps"
          check-strictly
          clearable
          placeholder="请选择文件夹"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['compo:attachment:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['compo:attachment:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"> 
      <el-table-column label="所属软件" align="center" prop="baseInfoId">
        <template #default="{ row }">
          {{ getBaseInfoName(row.baseInfoId) }}
        </template>
      </el-table-column>
      <el-table-column label="文件夹" align="center" prop="dirId">
        <template #default="{ row }">
          {{ getFileDirName(row.dirId) }}
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMPO_SOFTWARE_FILE_TYPE" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="文件名" align="center" prop="fileName" />
      <el-table-column label="文件路径" align="center" prop="filePath" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['compo:attachment:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['compo:attachment:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AttachmentForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AttachmentApi, AttachmentVO } from '@/api/compo/compoAttachment'
import { BaseInfoApi, BaseInfoOptionVO } from '@/api/compo/compoBaseInfo'
import { FileDirApi } from '@/api/compo/compoFileDir'
import { getNameById, convertToOptions } from '@/utils/compoDict'
import { defaultProps, handleTree } from '@/utils/tree'
import AttachmentForm from './AttachmentForm.vue'

// 定义树节点接口
interface TreeNode {
  id: number
  name: string
  children?: TreeNode[]
  [key: string]: any
}

/** 软件附件 列表 */
defineOptions({ name: 'CompoAttachment' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AttachmentVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const baseInfoList = ref<BaseInfoOptionVO[]>([]) // 所属软件列表数据
const baseInfoOptions = ref<any[]>([]) // 所属软件下拉选项
const fileDirTree = ref<TreeNode[]>([]) // 文件目录树形结构
const fileDirList = ref<any[]>([]) // 文件目录平铺列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  baseInfoId: undefined,
  type: undefined,
  fileName: undefined,
  createTime: [],
  dirId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const formRef = ref() // 表单 Ref

/** 获取所属软件信息 */
const getBaseInfoList = async () => {
  try {
    const data = await BaseInfoApi.listAllNormal()
    baseInfoList.value = data
    baseInfoOptions.value = convertToOptions(data)
  } catch (error) {
    console.error('获取所属软件列表失败:', error)
  }
}

/** 获取所属软件名称 */
const getBaseInfoName = (id: number) => {
  return getNameById(baseInfoList.value, id)
}

/** 获取文件目录树 */
const getFileDirTree = async () => {
  try {
    fileDirTree.value = []
    const data = await FileDirApi.getFileDirList({})
    fileDirList.value = data
    fileDirTree.value = handleTree(data, 'id', 'preId') as TreeNode[]
  } catch (error) {
    console.error('获取文件目录树失败:', error)
  }
}

/** 获取文件夹名称 */
const getFileDirName = (id: number) => {
  if (!id) return ''
  return getNameById(fileDirList.value, id)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AttachmentApi.getAttachmentPage(queryParams)
    
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AttachmentApi.deleteAttachment(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AttachmentApi.exportAttachment(queryParams)
    download.excel(data, '软件附件.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await Promise.all([getBaseInfoList(), getFileDirTree()])
  getList()
})
</script>